//
//  MNDWebViewController.m
//  miniwangdai2
//
//  Created by 谭伟 on 2017/4/13.
//  Copyright © 2017年 谭谭伟. All rights reserved.
//

#import "MNDWebViewController.h"
#import "MNDLoginNaviViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDBBSViewController.h"
#import "SYWebLoadingProgress.h"
#import "RSAUtil.h"
#import "MNDAboutViewController.h"
#import "UIImage+JKColor.h"

//银行存管设置密码跳转
#define kDepositSetPasswordReturn @"pay/pay_pwdset_jxreturn"
//银行存管自动投标跳转
#define kDepositAutoTenderReturn  @"pay/pay_autotender_jxreturn?"
//银行存管自动债转跳转
#define kDepositAutoTransferReturn @"pay/pay_autotransfer_jxreturn?"
//web版忘记交易密码
#define kWebForgotPassword         @"mobile/#/jiaoyi_pass"

//充值成功：pay/pay_result?type=recharge&state=success&channel=app
#define kRechargeSuccessReturn     @"pay/pay_result?type=recharge&state=success"
//提现成功
#define kWithdrawReturnSuccess     @"pay/pay_result?type=withdraw&state=success"
//提现失败
#define kWithdrawReturnFailed      @"pay/pay_result?type=withdraw&state=fail"

#define kChannel                   @"channel=app"

//充值失败：pay/pay_result?type=recharge&state=fail&id=1041&channel=app  或者 mobile/#/home/3
#define kRechargeFailedReturn      @"mobile/#/home/3"
//充值失败
#define kRechargeReturn            @"mobile/#/home"
//充值后点立即投资
#define kRechargeReturnInvestment  @"pay/investment"
//继续充值
#define kRechargeReturnContinue    @"pay/recharge"

//继续提现
#define kWithdrawReturn            @"/mobile/#/tixian"
//提现后查看明细
#define kWithdrawRecordReturn      @"mobile/#/jiaoyi_jl"

//提现失败或者异常页
#define kWithdrawFailed            @"mobile/#/home/2"

//静态页面如新手指南等的返回事件
#define kWebPageBack               @"app://minidai.back"

//静态页面拨打客服电话
#define kCallService              @"app://minidai.call_service"

/*! 网页版登录 */
#define kWebPageLogin             @"miniwangdai.com/login"

//论坛页面
#define kBBSWebPage               @"bbs.miniwangdai.com"

//积分规则内部嵌入网页
#define kReguralContentURL @"https://bbs.miniwangdai.com/forum/detailed?forum_code=55ff82aba466b"

//客服页面
#define kServicePage             @"ntalker.com"

#define kPCHomePage              @"https://www.miniwangdai.com/"

#define kAboutUs                 @"about_mine"

#define kRepostScrollToTop       @"#page1"

/*! 银行转账页面点击复制按钮 */
#define kBankTransfer            @"lapp/recharge/copy?data="

@interface MNDWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
//记录充值成功状态 只在充值的时候用到
@property (nonatomic) BOOL rechargeSuccess;

//记录提现成功状态，根据此状态点击返回按钮后返回账户中心
@property (nonatomic) BOOL withdrawSuccess;

/*! 记录跳转网页登录前的链接 */
@property (copy, nonatomic) NSString *absoluteUrl;

@property (strong, nonatomic) UIButton *closeButton;

@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;

@end

@implementation MNDWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (self.naviBarHidden) {
        self.makeFullScreen = YES;
    }
    
    [self initialWebView];
    
    [self initialBackButton];
    
    if ([self.webViewUrl containsString:kBBSWebPage]) {
        self.title = @"蜜柚社区";
    }
}

//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    NSLog(@"statusBar.backgroundColor--->%@",statusBar.backgroundColor);
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [self.closeButton setTitleColor:[UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0] forState:UIControlStateNormal];
    [self.closeButton addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.closeButton setFrame:CGRectMake(0, 0, 40, 30)];
    [self.closeButton setHidden:YES];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:self.closeButton];
//    [closeItem setTintColor: [UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0]];
    
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItems = @[backBarButtonItem, closeItem];;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem, closeItem];
    }
}

- (void)closeAction:(id)sender {
    
    if (self.presentingViewController) {
        //present方式
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            if (self.rechargeSuccess) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"recharge_back" object:nil];
            }
            
            if (self.isFromRecharge) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"recharge_continue" object:nil];
            }
            
            if (self.withdrawSuccess) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"withdraw_back" object:nil];
            }
        }];
    } else{
        //push方式
        [self.navigationController popViewControllerAnimated:YES];
    }
    [self clearWebViewCookies];
}


- (void)backAction:(id)sender {
    
    if ([self.webView canGoBack] && [self.webViewUrl containsString:kBBSWebPage]) {
        if (self.isFromIntegral) {
            [self.navigationController setNavigationBarHidden:YES animated:NO];
        }
        [self.webView goBack];
        [self.closeButton setHidden:NO];
        return;
    }
    if ([self.webView canGoBack] && self.isFromIntegral) {
        
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        [self.webView goBack];
        [self.closeButton setHidden:NO];
        return;
    }
    
    [self closeAction:nil];
}

- (void)clearWebViewCookies {
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //缓存web清除
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void) initialWebView {
    
    if (![MNDLoginUserModel isUserLogin]) {
        [self clearWebViewCookies];
    }
    
    self.webView = [[UIWebView alloc] init];
    self.webView.backgroundColor = kColorBackground;
    self.webView.scrollView.bounces = NO;
//    self.webView.detectsPhoneNumbers = NO;
    
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    self.webView.scalesPageToFit = YES;
    
    self.webView.delegate = self;
    
    if (self.loadType == LoadTypeLink) {

        if ([MNDLoginUserModel isUserLogin]) {
            NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
            NSLog(@"url: %@", urlStr);
            NSURL *url = [NSURL URLWithString: urlStr];
            NSURLRequest *request = [self configRequestHeaderFileds:url];

            [self.webView loadRequest:request];
        } else {
            NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
            NSLog(@"url: %@", urlStr);
            NSURL *url = [NSURL URLWithString: urlStr];
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
            [self.webView loadRequest:request];
        }
    } else if (self.loadType == LoadTypeHTMLString){
        [self.webView loadHTMLString:self.webViewUrl baseURL:nil];
    }
    
    [self.view beginLoading];
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

#pragma mark -UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    
    request = [mutableRequest copy];
    
    NSString *absoluteStr = request.URL.absoluteString;
    
    if (![absoluteStr containsString:kWebPageLogin]) {
        self.absoluteUrl = absoluteStr;
    }
    
    if ([absoluteStr isEqualToString:kPCHomePage]) {
        return NO;
    }
    
    NSLog(@"%@",absoluteStr);
    if ([absoluteStr isEqualToString:kMainPageURLStr]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        return NO;
    }
    
    if ([absoluteStr containsString:kDepositSetPasswordReturn]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        });
        
        return NO;
    }
    
    if ([absoluteStr containsString:kDepositAutoTenderReturn]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        });
        return NO;
    }
    
    if ([absoluteStr containsString:kDepositAutoTransferReturn]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        });
        return NO;
    }
    
    if ([absoluteStr containsString:kRechargeReturnInvestment]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"recharge_investment" object:nil];
        }];
        return NO;
    }
    
    if ([absoluteStr containsString:kRechargeSuccessReturn]) {
        self.rechargeSuccess = YES;
    }
    
    if ([absoluteStr containsString:kRechargeReturnContinue]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"recharge_continue" object:nil];
        }];
        return NO;
    }
    
    if ([absoluteStr containsString:kRechargeFailedReturn]) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"recharge_failed" object:nil];
        }];
        return NO;
    }
    
    if ([absoluteStr containsString:kWithdrawReturnSuccess]) {
        self.withdrawSuccess = YES;
    }
    //继续提现
    if ([absoluteStr containsString:kWithdrawReturn]) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"withdraw_result" object:nil];
        }];
        return NO;
    }
    //提现后查看交易记录
    if ([absoluteStr containsString:kWithdrawRecordReturn]) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"withdraw_record" object:nil];
        }];
        return NO;
    }
    //提现失败或异常
    if ([absoluteStr containsString:kWithdrawFailed]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        return NO;
    }
    
    if ([absoluteStr containsString:kWebPageBack]) {
        if (webView.canGoBack) {
            [webView goBack];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
        return NO;
    }
    
    if ([absoluteStr containsString:kCallService]) {
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", kServicePhoneNumber];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        return NO;
    }
    
    if ([absoluteStr containsString:kWebPageLogin] && !self.encodeUserCode && self.loadType != LoadTypeHTMLString) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self goLoginVC];
        });
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:kReguralContentURL] && self.isFromIntegral) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            MNDBBSViewController *bbsVC = [[MNDBBSViewController alloc] init];
            bbsVC.url = request.URL.absoluteString;
            bbsVC.shouldHideNaviBarWhenDismiss = YES;
            [self.navigationController pushViewController:bbsVC animated:YES];
        });
        
        return NO;
    }
    if ([request.URL.absoluteString containsString:kUserGuideServiceCenter]) {
        MNDBBSViewController *bbsVC = [[MNDBBSViewController alloc]init];
        bbsVC.url = kCustomerServiceURLStr;
//        bbsVC.title = @"在线客服";
        bbsVC.isCustomService = YES;
        bbsVC.shouldHideNaviBarWhenDismiss = YES;
        bbsVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bbsVC animated:YES];
        return NO;
    }
    
    //关于我们
    if ([request.URL.absoluteString containsString:kAboutUs]) {
    
    }
    //忘记交易密码
    if ([request.URL.absoluteString containsString:kWebForgotPassword]) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
        UINavigationController *naviVC = [storyboard instantiateViewControllerWithIdentifier:@"ResetPassworddNaviVC"];
        
        [self presentViewController:naviVC animated:YES completion:^{
            
        }];
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:kBankTransfer]) {
        NSString *requestUrlStr = request.URL.absoluteString;
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSRange range = [requestUrlStr rangeOfString:@"data="];
        pasteboard.string = [[requestUrlStr substringFromIndex:(range.location + 5)] stringByRemovingPercentEncoding];
        [NetworkProgressHUD showHudMsg:@"内容已复制到剪切板"];
        return NO;
    }
    
//    if ([request.URL.absoluteString containsString:kRepostScrollToTop]) {
//        
//        if ([self.webView subviews]){
//            
//            UIScrollView* scrollView = [[self.webView subviews] objectAtIndex:0];
//            //CGPointMake(0, 0)回到顶部
//            [scrollView setScrollsToTop:YES];
//        }
//        return NO;
//    }
    
    return YES;
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        
        CGFloat yPosition = 0.0;
//        if (kScreenHeight >= 812) {
//            yPosition = 24;
//        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
        //        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self.webLoadingProgress startProgressAnimation];
//    self.webLoadingProgress = [SYWebLoadingProgress addToView:webView animationPosition:AnimationPosition_Top style:LoadingPregressType_Noraml progressColor:kColorBlue];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress completedProgressAnimation];
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    
    if (self.isCircleReport) {
        NSString *cssString = @"img{width:100%}"; // 1
        NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2
        NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3
        [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString];
    }
    
    if ([webView.request.URL.absoluteString containsString:kServicePage]) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.navigationController setNavigationBarHidden:NO animated:NO];
//            [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('chat-view-window-header-back')[0].style.display='none';"];
//            self.title = @"在线客服";
        });
    } else {
        
        [self.navigationController setNavigationBarHidden:self.naviBarHidden animated:NO];
    }
    
    if ([webView.request.URL.absoluteString containsString:kBBSWebPage] && self.isFromIntegral) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.title = @"蜜柚社区";
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        });
        
    }
    [self.view endLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.view endLoading];
    [self.webLoadingProgress completedProgressAnimation];
    if (error.code == -999) {
        return;
    }
    
    if (error.code == 102) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    });
    
    NSLog(@"error: %@", error);
    
    [NetworkProgressHUD showHudNetworkError:error];
    WeakSelf(self);
    SYBlankPageType blankType = [self.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView reload];
            [weakself.view beginLoading];
        });
        
    }];
}

- (void)goLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    MNDLoginNaviViewController *naviVC = [storyboard instantiateInitialViewController];
    
    WeakSelf(self);
    naviVC.loginCompletedBlock = ^(BOOL loginSuccess) {
      
        if (loginSuccess) {
            NSLog(@"request url: %@", self.absoluteUrl);
            [weakself.webView removeFromSuperview];
            [weakself initialWebView];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself backAction:nil];
            });
        }
    };
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

- (NSMutableURLRequest *)configRequestHeaderFileds: (NSURL *)url {
    // 添加请求头信息
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSString *userCode = [self rsaEncode: user.user_code];
    
    [request setValue:userCode forHTTPHeaderField:@"USERCODE"];
    
    return request;
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
//    [self clearWebViewCookies];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
}

- (void)dealloc {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 设置cookie
 */
- (void)setCookies {
    if ([MNDLoginUserModel isUserLogin]) {
        
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        
        NSDictionary *dictCookieUId;
        
        dictCookieUId = @{
                          NSHTTPCookieName: @"user_code",
                          NSHTTPCookieValue: user.user_code,
                          NSHTTPCookiePath: @"/",
                          NSHTTPCookieVersion: @"0",
                          NSHTTPCookieDomain: @".miniwangdai.com"
                          };

        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dictCookieUId];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

@end
